package com.test.platform.controller;

import com.test.platform.model.User;
import com.test.platform.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Map<String, String> request) {
        try {
            String username = request.get("username");
            String password = request.get("password");
            String email = request.get("email");

            User user = userService.register(username, password, email);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "注册成功");
            response.put("user", Map.of(
            "username", user.getUsername(),
            "email", user.getEmail(),
            "createTime", user.getCreateTime()
            ));
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/check")
    public ResponseEntity<?> checkLoginStatus() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null) {
            return ResponseEntity.status(401)
                .body(Map.of(
                    "status", "error",
                    "message", "未登录"
                ));
        }

        boolean isAuthenticated = auth.isAuthenticated() && 
                                !(auth instanceof AnonymousAuthenticationToken);
        
        if (isAuthenticated) {
            return ResponseEntity.ok()
                .body(Map.of(
                    "status", "success",
                    "message", "已登录",
                    "user", auth.getName()
                ));
        } else {
            return ResponseEntity.status(401)
                .body(Map.of(
                    "status", "error",
                    "message", "未登录"
                ));
        }
    }
}